package com.blankj.utilcode.util;

import android.text.TextUtils;
import android.util.Log;

/**
 * Description: 脱敏工具类<br>
 *
 * @author King.Zi<br>
 * @date 2022/7/2<br>
 * Email: 78688689@qq.com
 */
public class DesensitizedUtil {
    /**
     * 姓名脱敏
     * 规则：
     * 1、两位姓名，如：王小      置换为     王*
     * 2、大于两位，如：王小红     置换为    王*红
     * 王张小红   置换为    王*红
     *
     * @param name
     * @return
     */
    public static String desensitizedName(String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.length() == 2) {
                name = name.replaceAll("(.).+", "$1*");
            }
            if (name.length() > 2) {
                name = name.replaceAll("(.).+(.)", "$1*$2");
            }
        }
        return name;
    }

    /**
     * 手机号脱敏
     * 规则：保留前三后四，如：18812349876  置换为 188****9876
     *
     * @param phone
     * @return
     */
    public static String desensitizedPhone(String phone) {
        if (!TextUtils.isEmpty(phone)) {
            phone = phone.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
        }
        return phone;
    }

    /**
     * 身份证脱敏（支持15位和18位）,保留前六后三
     *
     * @param idCard
     * @return
     */
    public static String desensitizedIdNumber(String idCard) {
        return desensitizedIdNumber(4, idCard);
    }

    /**
     * 身份证脱敏（支持15位和18位）
     * 规则：默认保留前六后三，如：123456789123456789 置换为 123456*********789
     *
     * @param idCard
     * @return
     */
    public static String desensitizedIdNumber(int prefixRetainCount, String idCard) {
        int id15Len = 15;
        int id18Len = 18;
        if (!TextUtils.isEmpty(idCard)) {
            int count = 0;
            if (idCard.length() == id15Len) {
                count = id15Len - 3 - prefixRetainCount;
                if (count <= 0) {
                    count = 6;
                    prefixRetainCount = 6;
                }
            } else if (idCard.length() == id18Len) {
                count = id18Len - 3 - prefixRetainCount;
                if (count <= 0) {
                    count = 9;
                    prefixRetainCount = 6;
                }
            }

            String starts = "";
            for (int i = 0; i < count; i++) {
                starts = starts + "*";
            }

            idCard = idCard.replaceAll("(\\w{" + prefixRetainCount + "})\\w*(\\w{3})", "$1" + starts + "$2");
        }
        return idCard;
    }
}
